package com.example.experiment3.service;

import com.example.experiment3.entity.RegionEntity;
import com.sun.net.httpserver.Headers;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service("regionService")
@EnableScheduling
public class RegionService implements InitializingBean {

    @Value("${CSVurl}")
    String url;
    List<RegionEntity> regionEntitys=new ArrayList<RegionEntity>();

    public List<RegionEntity> getRegionEntitys() {
        return regionEntitys;
    }

    public List<RegionEntity> getAllData() throws IOException {
        regionEntitys.clear();
        RequestEntity<Void> requestEntity=RequestEntity.get(URI.create(url))
                .headers(httpHeaders->httpHeaders.add("User-Agent","Mozilla/5.0"))
                .build();
        ResponseEntity<Resource> exchange=new RestTemplate().exchange(requestEntity,Resource.class);
        Resource body=exchange.getBody();
        InputStream inputStream=body.getInputStream();
        Reader reader=new InputStreamReader(inputStream);
        /*Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(reader);*/
        CSVParser csvParser=new CSVParser(reader,CSVFormat.EXCEL.withHeader());
        for (CSVRecord record : csvParser) {
                RegionEntity regionEntity = new RegionEntity();
                regionEntity.setCountry(record.get("Country/Region"));
                regionEntity.setProvince(record.get("Province/State"));
                regionEntity.setTotal(Integer.parseInt(record.get(record.size() - 1)));
                regionEntity.setIncreased(Integer.parseInt(record.get(record.size() - 1)) - Integer.parseInt(record.get(record.size() - 2)));
                regionEntitys.add(regionEntity);
            }
            return regionEntitys;
    }
    public List<RegionEntity> getCountryProvinceData(String country,String province) throws IOException {
        return regionEntitys.stream().filter((RegionEntity regionEntity)->{
            if (!"".equals(country) && !country.equals(regionEntity.getCountry()) ||
                    !"".equals(province) && !province.equals(regionEntity.getProvince())) {
                return false;
            }
            return true;
        })
                .collect(Collectors.toList());
    }

    @Scheduled(cron="0 0 1 * * *")
    public void fetchCoronaVirusData() throws IOException {
        getAllData();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        fetchCoronaVirusData();
    }
}
